<template>
  <AdminLayout>
    <el-card class="class-list-card">
      <template #header>
        <div class="card-header">
          <h2>班级列表</h2>
          <el-button type="primary" @click="handleAddClass">
            <el-icon><Plus /></el-icon>
            添加班级
          </el-button>
        </div>
      </template>

      <!-- 搜索和筛选区域 -->
      <div class="search-container">
        <el-input
          v-model="searchKeyword"
          placeholder="请输入班级名称搜索"
          prefix-icon="Search"
          clearable
          style="width: 300px; margin-right: 15px"
        />
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="handleReset">重置</el-button>
      </div>

      <el-table :data="filteredClassList" style="width: 100%">
        <el-table-column prop="classId" label="班级ID" width="80" />
        <el-table-column prop="className" label="班级名称" width="180" />
        <el-table-column prop="grade" label="年级" width="100" />
        <el-table-column prop="studentCount" label="学生人数" width="120">
          <template #default="{ row }">
            {{ row.studentCount || 0 }}
          </template>
        </el-table-column>
        <el-table-column prop="headTeacherName" label="班主任" width="120">
          <template #default="{ row }">
            {{ row.headTeacherName || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEditClass(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="handleDeleteClass(row.classId)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </AdminLayout>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { get, postJson } from '../../utils/api'
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
import AdminLayout from '../../components/admin/AdminLayout.vue'

const router = useRouter()

// 班级列表数据
const classList = ref<any[]>([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const searchKeyword = ref('')

// 过滤后的班级列表
const filteredClassList = computed(() => {
  if (!searchKeyword.value) {
    return classList.value
  }
  return classList.value.filter(cls => 
    cls.className.toLowerCase().includes(searchKeyword.value.toLowerCase())
  )
})

// 加载班级列表
const loadClassList = async () => {
  try {
    // 假设后端有班级查询接口
    const result = await get('/class/query')
    if (result.code === 200) {
      classList.value = result.data || []
      total.value = result.dataCount || 0
    } else {
      ElMessage.error('加载班级列表失败')
      // 如果接口不存在，使用模拟数据
      classList.value = getMockClassData()
      total.value = classList.value.length
    }
  } catch (error) {
    console.error('加载班级列表错误:', error)
    ElMessage.warning('网络错误，使用模拟数据')
    // 使用模拟数据
    classList.value = getMockClassData()
    total.value = classList.value.length
  }
}

// 模拟班级数据
const getMockClassData = () => [
  {
    classId: 1,
    className: '计算机科学与技术1班',
    grade: '2023',
    studentCount: 35,
    headTeacherName: '张老师',
    createTime: '2023-09-01T00:00:00'
  },
  {
    classId: 2,
    className: '软件工程2班',
    grade: '2023',
    studentCount: 32,
    headTeacherName: '李老师',
    createTime: '2023-09-01T00:00:00'
  },
  {
    classId: 3,
    className: '数据科学与大数据技术班',
    grade: '2023',
    studentCount: 28,
    headTeacherName: '王老师',
    createTime: '2023-09-01T00:00:00'
  }
]

// 格式化日期时间
const formatDateTime = (dateTimeString: string) => {
  if (!dateTimeString) return ''
  const date = new Date(dateTimeString)
  return date.toLocaleDateString('zh-CN')
}

// 处理添加班级
const handleAddClass = () => {
  router.push('/admin/class/add')
}

// 处理编辑班级
const handleEditClass = (classData: any) => {
  // 这里可以跳转到编辑页面，并传递班级ID
  ElMessage.info('编辑功能开发中')
}

// 处理删除班级
const handleDeleteClass = async (classId: number) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除该班级吗？删除后将不可恢复。',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    // 假设后端有班级删除接口
    const result = await get(`/class/delete?id=${classId}`)
    if (result.code === 200) {
      ElMessage.success('删除成功')
      loadClassList() // 重新加载列表
    } else {
      ElMessage.error(result.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除班级错误:', error)
      ElMessage.warning('删除失败或接口未实现')
    }
  }
}

// 搜索处理
const handleSearch = () => {
  // 在实际应用中，可以重新调用API进行搜索
  console.log('搜索班级:', searchKeyword.value)
}

// 重置搜索
const handleReset = () => {
  searchKeyword.value = ''
  loadClassList()
}

// 分页相关处理
const handleSizeChange = (size: number) => {
  pageSize.value = size
  loadClassList()
}

const handleCurrentChange = (current: number) => {
  currentPage.value = current
  loadClassList()
}

// 组件挂载时加载数据
onMounted(() => {
  loadClassList()
})
</script>

<style scoped>
.class-list-card {
  margin: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0;
}

.card-header h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 500;
}

.search-container {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-table__fixed-right) {
  height: 100% !important;
}
</style>